package rjeutsky.tags;


import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;

import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class AuthenticationLevel extends SimpleTagSupport {
	public enum UserLevel
	{
		GUEST,
		USER,
		ADMIN
	};
	
	private UserLevel userLevel = UserLevel.GUEST;
	
	public String getUserLevelString()
	{
		return userLevel.name();
	}
	
	public void setUserLevelString(String userLevelString)
	{
		if (userLevel == null)
			this.userLevel = UserLevel.GUEST;
		this.userLevel = UserLevel.valueOf(userLevelString); 
	}
	
	private boolean isAdmin()
	{
		return false;
	}
	
	int compareUserLevels(UserLevel first, UserLevel second)
	{
		if (first == second)
			return 0;
		if (first == UserLevel.ADMIN)
			return -1;
		if (second == UserLevel.ADMIN)
			return 1;
		if (first == UserLevel.GUEST)
			return 1;
		return -1;
		
	}
	
	private boolean isAuthenticated(HttpSession session, PageContext pageContext)
	{
		UserLevel currentUserLevel = UserLevel.GUEST;
		if (session.getAttribute("currentUser")!= null)
			currentUserLevel = UserLevel.USER;
		else
		{
			boolean isAdmin = isAdmin();
			pageContext.setAttribute("isAdmin", isAdmin);
			if (isAdmin())
			{
				currentUserLevel = UserLevel.ADMIN;
			}
		}
		return compareUserLevels(userLevel, currentUserLevel) >=0;
	}
	
	public void doTag() throws JspException {
		
		PageContext pageContext = (PageContext) getJspContext();
		
		 if (!isAuthenticated(pageContext.getSession(), pageContext))
			try {
				pageContext.forward("Login.jsp");
			} catch (Exception e) {
				throw new JspException("Cannot forward page", e);
			}
	}
	
}
